package com.ia.aistream.manager.framework.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ia.aistream.common.constant.Constants;
import com.ia.aistream.common.core.domain.AjaxResult;
import com.ia.aistream.common.exception.base.CustomException;
import com.ia.aistream.common.utils.StringUtils;
import com.ia.aistream.common.utils.http.HttpHelper;
import com.ia.aistream.manager.authen.ITokenManager;
import com.ia.aistream.manager.authen.conf.AuthenConf;
import com.ia.aistream.manager.framework.interceptor.annotation.UserAuthorization;
import com.ia.aistream.mapper.system.SysUserMapper;
import com.ia.aistream.model.system.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @author chenjunsheng
 */
@Slf4j
@Component
public class UserTokenInterceptor extends HandlerInterceptorAdapter {
    /**
     * 令牌前缀
     */
    private static final String TOKEN_PREFIX = "Bearer";
    @Autowired
    private AuthenConf authenConf;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private ITokenManager tokenManager;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return super.preHandle(request, response, handler);
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //不需要登录校验
        UserAuthorization authorization = method.getAnnotation(UserAuthorization.class);
        if (authorization == null) {
            return true;
        }

        SysUser sysUser = (SysUser) request.getAttribute(Constants.USER_ATTR_KEY);
        if (sysUser == null) {
            String token = this.getToken(request);
            if (StringUtils.isNotEmpty(token)) {
                sysUser = tokenManager.getTokenUser(token);
            }
            if (StringUtils.isNull(sysUser)) {
                if (authorization.mustCheck()) {
                    log.error("请求用户为空信息为空");
                    throw new CustomException("请求用户为空");
                } else {
                    return true;
                }
            }
        }
        SysUser user = userMapper.selectById(sysUser.getUserId());
        if (StringUtils.isNull(user)) {
            log.error("账号不存在，请求用户ID为：" + user.getUserId());
            throw new CustomException("账号不存在");
        }
        request.setAttribute(Constants.USER_ATTR_KEY, user);
        return true;
    }

    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(authenConf.getToken().getHeader());
        if (StringUtils.isNotBlank(token)) {
            return token.replaceFirst(TOKEN_PREFIX, "").trim();
        }

        token = request.getParameter(authenConf.getToken().getTokenKey());
        if (StringUtils.isNotBlank(token)) {
            return token;
        }

        String json = HttpHelper.getBodyString(request);
        if (StringUtils.isBlank(json)) {
            return null;
        }

        JSONObject object = JSON.parseObject(json);
        return object.getString(authenConf.getToken().getTokenKey());
    }
}
